/**
 * Matrix Framework Keycloak Theme - Login Enhancement
 * Matrix Framework登录页面增强功能
 */

/**
 * 登录表单增强类
 */
export class LoginFormEnhancer {
    constructor(options = {}) {
        this.options = {
            formId: 'kc-form-login',
            showPasswordToggle: true,
            enableValidation: true,
            enableAutoFocus: true,
            enableEnterKeySubmit: true,
            ...options
        };

        this.form = null;
        this.inputs = {};
        this.validators = {};
        this.isSubmitting = false;
    }

    /**
     * 初始化登录表单增强功能
     */
    init() {
        this.form = document.getElementById(this.options.formId);
        if (!this.form) {
            console.warn(`Login form with id "${this.options.formId}" not found`);
            return;
        }

        this.cacheElements();
        this.bindEvents();
        this.initPasswordToggle();
        this.initValidation();
        this.initAutoFocus();
        this.initAnimations();
        this.initAnalytics();
    }

    /**
     * 缓存DOM元素
     */
    cacheElements() {
        this.inputs = {
            username: document.getElementById('username'),
            password: document.getElementById('password'),
            rememberMe: document.getElementById('rememberMe')
        };

        this.elements = {
            submitButton: document.getElementById('kc-login'),
            loadingOverlay: document.getElementById('loadingOverlay'),
            formGroups: this.form.querySelectorAll('.matrix-form-group'),
            tenantBadge: document.querySelector('.tenant-badge')
        };
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 表单提交事件
        this.form.addEventListener('submit', (e) => {
            if (this.options.enableValidation) {
                const isValid = this.validateForm();
                if (!isValid) {
                    e.preventDefault();
                    return;
                }
            }

            this.handleFormSubmit(e);
        });

        // 输入框焦点事件
        Object.values(this.inputs).forEach(input => {
            if (input) {
                input.addEventListener('focus', (e) => this.handleInputFocus(e));
                input.addEventListener('blur', (e) => this.handleInputBlur(e));
                input.addEventListener('input', (e) => this.handleInputChange(e));
            }
        });

        // Enter键提交
        if (this.options.enableEnterKeySubmit) {
            this.inputs.username?.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    this.inputs.password?.focus();
                }
            });
        }

        // 防止重复提交
        this.elements.submitButton?.addEventListener('click', () => {
            this.setSubmittingState(true);
        });

        // 页面可见性变化时重置提交状态
        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'visible') {
                this.setSubmittingState(false);
            }
        });
    }

    /**
     * 初始化密码显示/隐藏切换
     */
    initPasswordToggle() {
        if (!this.options.showPasswordToggle || !this.inputs.password) {
            return;
        }

        const toggleButton = this.inputs.password.parentElement.querySelector('.password-toggle');
        if (!toggleButton) {
            return;
        }

        toggleButton.addEventListener('click', () => {
            this.togglePasswordVisibility();
        });
    }

    /**
     * 初始化表单验证
     */
    initValidation() {
        if (!this.options.enableValidation) {
            return;
        }

        // 用户名验证规则
        this.validators.username = {
            validate: (value) => {
                if (!value || value.trim().length < 3) {
                    return '用户名至少需要3个字符';
                }
                if (!/^[\w@.-]+$/.test(value)) {
                    return '用户名包含无效字符';
                }
                return null;
            },
            message: '请输入有效的用户名或邮箱'
        };

        // 密码验证规则
        this.validators.password = {
            validate: (value) => {
                if (!value || value.length < 1) {
                    return '请输入密码';
                }
                return null;
            },
            message: '请输入密码'
        };
    }

    /**
     * 初始化自动聚焦
     */
    initAutoFocus() {
        if (!this.options.enableAutoFocus) {
            return;
        }

        // 延迟聚焦，确保动画完成
        setTimeout(() => {
            if (this.inputs.username && !this.inputs.username.value) {
                this.inputs.username.focus();
            } else if (this.inputs.password) {
                this.inputs.password.focus();
            }
        }, 500);
    }

    /**
     * 初始化动画效果
     */
    initAnimations() {
        // 表单组渐入动画
        this.elements.formGroups.forEach((group, index) => {
            group.style.opacity = '0';
            group.style.transform = 'translateY(20px)';

            setTimeout(() => {
                group.style.transition = 'all 0.5s ease';
                group.style.opacity = '1';
                group.style.transform = 'translateY(0)';
            }, index * 100);
        });

        // Logo动画
        const logo = document.querySelector('.matrix-logo img');
        if (logo) {
            logo.addEventListener('load', () => {
                logo.style.animation = 'fadeInDown 0.8s ease';
            });
        }
    }

    /**
     * 初始化分析跟踪
     */
    initAnalytics() {
        // 跟踪页面加载
        this.trackEvent('login_page_view', {
            realm: window.MatrixTheme?.realm || 'unknown',
            tenant_id: window.MatrixTheme?.tenantId || 'unknown'
        });

        // 跟踪输入框焦点
        Object.entries(this.inputs).forEach(([name, input]) => {
            if (input) {
                input.addEventListener('focus', () => {
                    this.trackEvent('login_form_field_focus', { field: name });
                });
            }
        });
    }

    /**
     * 处理输入框焦点
     */
    handleInputFocus(e) {
        const formGroup = e.target.closest('.matrix-form-group');
        if (formGroup) {
            formGroup.classList.add('focused');
        }

        // 移除错误状态
        this.removeFieldError(e.target);
    }

    /**
     * 处理输入框失焦
     */
    handleInputBlur(e) {
        const formGroup = e.target.closest('.matrix-form-group');
        if (formGroup) {
            formGroup.classList.remove('focused');
        }

        // 触发验证
        if (this.options.enableValidation) {
            this.validateField(e.target);
        }
    }

    /**
     * 处理输入变化
     */
    handleInputChange(e) {
        // 实时验证
        if (this.options.enableValidation && e.target.value) {
            this.validateField(e.target);
        }
    }

    /**
     * 处理表单提交
     */
    handleFormSubmit(e) {
        // 显示加载状态
        showLoading();

        // 跟踪提交事件
        this.trackEvent('login_form_submit', {
            realm: window.MatrixTheme?.realm || 'unknown',
            has_username: !!this.inputs.username?.value,
            has_remember_me: this.inputs.rememberMe?.checked
        });
    }

    /**
     * 设置提交状态
     */
    setSubmittingState(isSubmitting) {
        this.isSubmitting = isSubmitting;

        if (this.elements.submitButton) {
            this.elements.submitButton.disabled = isSubmitting;

            if (isSubmitting) {
                this.elements.submitButton.innerHTML = `
                    <i class="fas fa-spinner fa-spin"></i>
                    <span>登录中...</span>
                `;
            } else {
                this.elements.submitButton.innerHTML = `
                    <i class="fas fa-sign-in-alt"></i>
                    <span>${this.elements.submitButton.dataset.originalText || '登录'}</span>
                `;
            }
        }
    }

    /**
     * 切换密码可见性
     */
    togglePasswordVisibility() {
        if (!this.inputs.password) {
            return;
        }

        const passwordField = this.inputs.password;
        const toggleButton = passwordField.parentElement.querySelector('.password-toggle');
        const toggleIcon = toggleButton?.querySelector('i');

        if (passwordField.type === 'password') {
            passwordField.type = 'text';
            if (toggleIcon) {
                toggleIcon.classList.remove('fa-eye');
                toggleIcon.classList.add('fa-eye-slash');
            }
            toggleButton?.setAttribute('title', '隐藏密码');
        } else {
            passwordField.type = 'password';
            if (toggleIcon) {
                toggleIcon.classList.remove('fa-eye-slash');
                toggleIcon.classList.add('fa-eye');
            }
            toggleButton?.setAttribute('title', '显示密码');
        }

        // 跟踪密码可见性切换
        this.trackEvent('password_visibility_toggled', {
            visible: passwordField.type === 'text'
        });
    }

    /**
     * 验证表单
     */
    validateForm() {
        let isValid = true;

        // 验证所有字段
        Object.entries(this.inputs).forEach(([name, input]) => {
            if (input && this.validators[name]) {
                const fieldValid = this.validateField(input);
                if (!fieldValid) {
                    isValid = false;
                }
            }
        });

        return isValid;
    }

    /**
     * 验证单个字段
     */
    validateField(field) {
        if (!field || !this.validators[field.id]) {
            return true;
        }

        const validator = this.validators[field.id];
        const error = validator.validate(field.value);

        if (error) {
            this.showFieldError(field, error);
            return false;
        } else {
            this.removeFieldError(field);
            return true;
        }
    }

    /**
     * 显示字段错误
     */
    showFieldError(field, message) {
        const formGroup = field.closest('.matrix-form-group');
        if (!formGroup) return;

        // 移除已存在的错误消息
        this.removeFieldError(field);

        // 添加错误状态类
        formGroup.classList.add('error');
        field.classList.add('error');

        // 创建错误消息元素
        const errorElement = document.createElement('div');
        errorElement.className = 'field-error-message';
        errorElement.textContent = message;

        formGroup.appendChild(errorElement);
    }

    /**
     * 移除字段错误
     */
    removeFieldError(field) {
        const formGroup = field.closest('.matrix-form-group');
        if (!formGroup) return;

        formGroup.classList.remove('error');
        field.classList.remove('error');

        const errorElement = formGroup.querySelector('.field-error-message');
        if (errorElement) {
            errorElement.remove();
        }
    }

    /**
     * 跟踪事件
     */
    trackEvent(eventName, data = {}) {
        // 这里可以集成Google Analytics或其他分析工具
        if (typeof gtag !== 'undefined') {
            gtag('event', eventName, data);
        } else if (window.dataLayer) {
            window.dataLayer.push({
                event: eventName,
                ...data
            });
        }

        // 开发模式下输出到控制台
        if (process.env.NODE_ENV === 'development') {
            console.log(`[Matrix Login] ${eventName}:`, data);
        }
    }
}

/**
 * 密码强度检测器
 */
export class PasswordStrengthChecker {
    constructor() {
        this.criteria = {
            minLength: 8,
            requireUppercase: true,
            requireLowercase: true,
            requireNumbers: true,
            requireSpecialChars: false
        };
    }

    /**
     * 检查密码强度
     */
    checkStrength(password) {
        const result = {
            score: 0,
            strength: 'weak',
            feedback: []
        };

        if (!password) {
            return result;
        }

        // 长度检查
        if (password.length >= this.criteria.minLength) {
            result.score += 1;
        } else {
            result.feedback.push(`密码至少需要${this.criteria.minLength}个字符`);
        }

        // 大写字母检查
        if (this.criteria.requireUppercase && /[A-Z]/.test(password)) {
            result.score += 1;
        } else if (this.criteria.requireUppercase) {
            result.feedback.push('需要包含大写字母');
        }

        // 小写字母检查
        if (this.criteria.requireLowercase && /[a-z]/.test(password)) {
            result.score += 1;
        } else if (this.criteria.requireLowercase) {
            result.feedback.push('需要包含小写字母');
        }

        // 数字检查
        if (this.criteria.requireNumbers && /\d/.test(password)) {
            result.score += 1;
        } else if (this.criteria.requireNumbers) {
            result.feedback.push('需要包含数字');
        }

        // 特殊字符检查
        if (this.criteria.requireSpecialChars && /[!@#$%^&*(),.?":{}|<>]/.test(password)) {
            result.score += 1;
        } else if (this.criteria.requireSpecialChars) {
            result.feedback.push('需要包含特殊字符');
        }

        // 计算强度等级
        if (result.score >= 4) {
            result.strength = 'strong';
        } else if (result.score >= 2) {
            result.strength = 'medium';
        } else {
            result.strength = 'weak';
        }

        return result;
    }
}

/**
 * 会话管理器
 */
export class SessionManager {
    constructor() {
        this.sessionKey = 'matrix_login_session';
        this.maxAge = 24 * 60 * 60 * 1000; // 24小时
    }

    /**
     * 保存登录会话
     */
    saveSession(userData, rememberMe = false) {
        const session = {
            userData,
            rememberMe,
            timestamp: Date.now(),
            expires: Date.now() + (rememberMe ? this.maxAge * 7 : this.maxAge)
        };

        try {
            if (rememberMe) {
                localStorage.setItem(this.sessionKey, JSON.stringify(session));
            } else {
                sessionStorage.setItem(this.sessionKey, JSON.stringify(session));
            }
        } catch (error) {
            console.warn('Failed to save session:', error);
        }
    }

    /**
     * 获取登录会话
     */
    getSession() {
        try {
            let sessionData = sessionStorage.getItem(this.sessionKey) ||
                             localStorage.getItem(this.sessionKey);

            if (!sessionData) {
                return null;
            }

            const session = JSON.parse(sessionData);

            // 检查会话是否过期
            if (Date.now() > session.expires) {
                this.clearSession();
                return null;
            }

            return session;
        } catch (error) {
            console.warn('Failed to retrieve session:', error);
            return null;
        }
    }

    /**
     * 清除登录会话
     */
    clearSession() {
        try {
            sessionStorage.removeItem(this.sessionKey);
            localStorage.removeItem(this.sessionKey);
        } catch (error) {
            console.warn('Failed to clear session:', error);
        }
    }

    /**
     * 检查会话是否有效
     */
    isSessionValid() {
        const session = this.getSession();
        return session !== null;
    }
}

/**
 * 工具函数
 */

/**
 * 显示加载状态
 */
export function showLoading() {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'flex';
    }
}

/**
 * 隐藏加载状态
 */
export function hideLoading() {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'none';
    }
}

/**
 * 切换语言菜单
 */
export function toggleLanguageMenu() {
    const languageMenu = document.getElementById('languageMenu');
    if (languageMenu) {
        languageMenu.classList.toggle('show');

        // 点击外部关闭菜单
        document.addEventListener('click', function closeMenu(e) {
            if (!e.target.closest('.language-dropdown')) {
                languageMenu.classList.remove('show');
                document.removeEventListener('click', closeMenu);
            }
        });
    }
}

/**
 * 切换语言
 */
export function changeLanguage(locale) {
    // 构建新的URL参数
    const url = new URL(window.location);
    url.searchParams.set('kc_locale', locale);

    // 重定向到新语言版本
    window.location.href = url.toString();

    // 跟踪语言切换
    if (typeof gtag !== 'undefined') {
        gtag('event', 'language_change', { locale });
    }
}

/**
 * 显示Toast通知
 */
export function showToast(message, type = 'info', duration = 5000) {
    const toast = document.createElement('div');
    toast.className = `matrix-toast matrix-toast-${type}`;
    toast.innerHTML = `
        <div class="toast-content">
            <i class="fas fa-${getToastIcon(type)}"></i>
            <span>${message}</span>
        </div>
    `;

    document.body.appendChild(toast);

    // 显示动画
    setTimeout(() => toast.classList.add('show'), 100);

    // 自动隐藏
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, duration);
}

/**
 * 获取Toast图标
 */
function getToastIcon(type) {
    const icons = {
        success: 'check-circle',
        error: 'exclamation-circle',
        warning: 'exclamation-triangle',
        info: 'info-circle'
    };
    return icons[type] || 'info-circle';
}

// 全局导出
window.MatrixLogin = {
    LoginFormEnhancer,
    PasswordStrengthChecker,
    SessionManager,
    showLoading,
    hideLoading,
    toggleLanguageMenu,
    changeLanguage,
    showToast
};